<template>
  <AdminLayout>
    <el-card class="add-teacher-card">
      <template #header>
        <div class="card-header">
          <h2>添加教师</h2>
        </div>
      </template>
      
      <el-form :model="teacherForm" :rules="rules" ref="teacherFormRef" label-width="120px"
                :disabled="submitting"
                class="teacher-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="teacherForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="teacherForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="teacherForm.confirmPassword" type="password" placeholder="请再次输入密码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="teacherForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="教师编号" prop="teacherNo">
          <el-input v-model="teacherForm.teacherNo" placeholder="请输入教师编号" />
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="teacherForm.title" placeholder="请输入职称（如：讲师、教授）" />
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-input v-model="teacherForm.department" placeholder="请输入所属部门" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="teacherForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
            <el-radio label="未知">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="teacherForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="teacherForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item>
          <div class="form-actions">
            <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { useRouter } from 'vue-router'
import { postJson } from '../../utils/api'
import AdminLayout from '../../components/admin/AdminLayout.vue'

const router = useRouter()

// 表单引用
const teacherFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 表单数据
const teacherForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  teacherNo: '',
  title: '',
  department: '',
  gender: '未知',
  phone: '',
  email: ''
})

// 提交状态
const submitting = ref(false)

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: (error?: Error) => void) => {
        if (value !== teacherForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  teacherNo: [
    {
      required: true,
      message: '请输入教师编号',
      trigger: 'blur'
    }
  ],
  title: [
    {
      required: false,
      message: '请输入职称',
      trigger: 'blur'
    }
  ],
  department: [
    {
      required: false,
      message: '请输入所属部门',
      trigger: 'blur'
    }
  ],
  gender: [
    {
      required: false,
      message: '请选择性别',
      trigger: 'change'
    }
  ],
  phone: [
    {
      required: false,
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: false,
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ]
})

// 提交表单
const handleSubmit = async () => {


  if (!teacherFormRef.value) return
  
  try {
    // 表单验证
    await teacherFormRef.value.validate()
    
    // 设置提交状态
    submitting.value = true
    
    // 准备请求数据 - 添加roleId参数，教师角色ID为2
    const submitData = {
      username: teacherForm.username,
      password: teacherForm.password,
      realName: teacherForm.realName,
      teacherNo: teacherForm.teacherNo || '',
      title: teacherForm.title || '',
      department: teacherForm.department || '',
      gender: teacherForm.gender,
      phone: teacherForm.phone || '',
      email: teacherForm.email || '',
      roleId: 2 // 教师角色ID
    }
    
    // 调用后端API添加教师
    const result = await postJson('/teacher/add', submitData)
    
    // 根据API返回结果处理
    if (result.code === 200) {
      ElMessage.success(result.msg || '添加教师成功')
      // 返回教师列表页面
      router.push('/admin/teacher/list')
    } else {
      ElMessage.error(result.msg || '添加失败')
    }
  } catch (error) {
    if (error !== false) { // 如果不是表单验证失败
      console.error('添加教师失败:', error)
      ElMessage.error('网络错误，请检查后端服务是否正常运行')
    }
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  // 返回教师列表页面
  router.push('/admin/teacher/list')
}
</script>

<style scoped>
.add-teacher-card {
  max-width: 600px;
  margin: 20px auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  font-weight: bold;
  font-size: 18px;
}

.teacher-form {
  padding: 20px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}
</style>

/* 全局样式重置，确保整个页面背景一致 */
<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body, html {
  width: 100% !important;
  height: 100% !important;
  background-color: #fff !important;
  overflow: hidden;
}

#app {
  width: 100% !important;
  height: 100% !important;
  background-color: #fff !important;
}
</style>